package com.alibaba.cloud.authorization.token;

import com.alibaba.cloud.authorization.api.feign.UserServiceFeign;
import com.alibaba.cloud.authorization.entity.AuthUserDetails;
import com.alibaba.cloud.authorization.entity.LoginUser;
import com.alibaba.cloud.authorization.tips.BaseTips;
import com.alibaba.framework.exception.BusinessException;
import com.alibaba.framework.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class UserDetailService implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailService.class);

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LoginUser loginUser = userServiceFeign.getLoginUser(username);
        if (Objects.isNull(loginUser)) {
            throw new BusinessException(BaseTips.USER_NOT_FOUND);
        }
        String dateTime = DateUtil.getDateTime();
        loginUser.setCreateTime(DateUtil.getDateTime());
        loginUser.setLoginTime(dateTime);
        loginUser.setUpdateTime(dateTime);
        return new AuthUserDetails(loginUser);
    }
}
